package us.wili.dev.common.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 * author: lefore
 * date: 2017/11/21
 */
public class EncryptUtil {

    protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private static final String HMAC_SHA1 = "HmacSHA1";
    private static final String ENCODING = "UTF-8";

    /**
     * 获取 MD5 加密字符串
     *
     * @param source
     * @return
     */
    public static String getMD5(String source) {
        try {
            byte[] sourceBytes = source.getBytes("UTF-8");
            return getMD5(sourceBytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取 HMAC-SHA1 加密字符串
     *
     * @param rawStr
     * @param secretKey
     * @return
     */
    public static String getHMACSHA1(String rawStr, String secretKey) {
        if (rawStr == null || rawStr.trim().length() == 0
                || secretKey == null || secretKey.trim().length() == 0) {
            return "";
        }
        try {
            byte[] rawStrByte = rawStr.getBytes(ENCODING);
            byte[] secretKeyByte = secretKey.getBytes(ENCODING);

            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyByte, HMAC_SHA1);
            Mac mac = Mac.getInstance(HMAC_SHA1);
            mac.init(secretKeySpec);
            byte[] rawHmac = mac.doFinal(rawStrByte);

            return getMD5(rawHmac);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取 MD5 加密字符串
     *
     * @param rawStr
     * @return
     */
    private static String getMD5(byte[] rawStr) {
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(rawStr);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}
